import {
    Avatar, Button,
    Dropdown,
    DropdownItem,
    DropdownMenu,
    DropdownTrigger,
    Input,
    Modal, ModalBody, ModalContent, ModalFooter, ModalHeader,
    NavbarContent, Spacer, Switch, Textarea, Tooltip, useDisclosure
} from "@nextui-org/react";
import {MailIcon, MoonIcon, SearchIcon, SunIcon} from "@nextui-org/shared-icons";
import React, {useEffect, useLayoutEffect, useState} from "react";
import {FiUser} from "react-icons/fi";
import {MdMoreTime} from "react-icons/md";
import UserInfoService from "@/app/service/userInfoService";
import cookie from "react-cookies";
import {Token, UserName} from "@/app/constants/authTokenConstants";
import {decodeFromBase64} from "next/dist/build/webpack/loaders/utils";
import Profile from "@/app/pages/profile/Profile";
import {KeyboardEvent} from "@react-types/shared/src/events";
import PubSub from "pubsub-js";
import {BiCertification, BiHotel, BiLogOutCircle, BiMehBlank} from "react-icons/bi";
import {useTheme} from "next-themes";
import {className} from "postcss-selector-parser";
import {Divider} from "@nextui-org/divider";
import ToastUtil from "@/app/utils/toastUtil";
import SettingPage from "@/app/components/profile/SettingPage";
import {SiNamebase} from "react-icons/si";
import {AiFillCamera} from "react-icons/ai";
import {CiFries} from "react-icons/ci";
import ModifyInfo from "@/app/service/ModifyInfo";

/**
 * 个人中心头像点击时的组件和状态
 * @param username
 * @param isExit
 * @param setExit
 * @param setSearchKey
 * @param setInSearch
 * @constructor
 */
export default function OnAuthenticatedNavbarContent({
                                                         username,
                                                         isExit,
                                                         setExit,
                                                         setSearchKey,
                                                         setInSearch
                                                     }: any) {
    const {isOpen, onOpen, onOpenChange} = useDisclosure();

    /*邮箱和创建时间状态*/
    const [nickname, setNickname] = useState('')
    const [avatar, setAvatar] = useState('');
    const [email, setEmail] = useState('');
    const [createTime, setCreateTime] = useState('');
    const [newAvatar, setNewAvatar] = useState('');

    /*const [info, setInfo] = useState({
        nickname: '',
        avatar: '',
        email: '',
        createTime: ''
    })
    const token = cookie.load(Token).substring(7) + "***********";*/


    /**
     * 加载数据
     */
    const [refresh, setRefresh] = useState(false);
    useLayoutEffect(() => {
        UserInfoService({setEmail, setCreateTime, setNickname, setAvatar}).then();
    }, [refresh])


    /**
     * 头像变化监听
     */
    const handleAvatarChange = (event: any) => {
        const file = event.target.files[0];
        if (file) {
            setNewAvatar(file);
            setAvatar(URL.createObjectURL(file));
        }
    }

    /**
     * 选择图片
     */
    const handleChoosePhoto = () => {
        const inputElement = document.createElement('input');
        inputElement.type = 'file';
        inputElement.accept = 'image/*';

        inputElement.onchange = (event) => {
            handleAvatarChange(event)
        };

        inputElement.click();
    };

    /**
     * 更新信息
     */
    function modifyUserInfo() {
        ModifyInfo(nickname, newAvatar).then(res => {
            if (res) {
                setRefresh(true)
            }
        });
    }

    /**打开i设置*/
    const [isOpenSet, onOpenSetChange] = useState(false);
    /**搜索数据*/
    const [inputValue, setInputValue] = useState('');
    const handleKeyDown = (e: KeyboardEvent) => {
        // noinspection JSDeprecatedSymbols
        if (e.keyCode === 13) {
            PubSub.publish('keyword', inputValue);
            setSearchKey(inputValue);
            setInSearch(true);
        }
    };

    /**
     * 主题切换
     */
    const {theme, setTheme} = useTheme()
    return (
        <>
            <NavbarContent as="div" className="items-center" justify="end">
                <Input
                    classNames={{
                        base: "lg:flex max-w-full sm:max-w-[7rem] h-8",
                        mainWrapper: "h-full",
                        input: "text-small",
                        inputWrapper: "h-full font-normal text-default-500 bg-default-400/20 dark:bg-default-500/20",
                    }}
                    placeholder="搜索文档..."
                    size="sm"
                    startContent={<SearchIcon fontSize={18}/>}
                    type="text"
                    variant={'bordered'}
                    onValueChange={(value) => {
                        setInputValue(value)
                    }}
                    onKeyDown={handleKeyDown}
                />
                <Dropdown placement="bottom-end"
                          className={`dark:text-white light:text-black `}
                          backdrop={"transparent"}
                          size={"sm"}>
                    <DropdownTrigger>
                        <Avatar
                            isBordered
                            as="button"
                            radius={"lg"}
                            className="transition-transform min-w-fit"
                            color="primary"
                            name={username}
                            size="sm"
                            src={avatar == '' ? "https://baiyunshan.flowus.cn/public%2Fe8be5d93-efd7-4efe-9da8-f41d86956b83%2F42428313-3e08-4d25-957c-64e18b5bb15f.jpg?img_process=/resize,w_1000/quality,q_100/" : avatar}
                        />
                    </DropdownTrigger>
                    <DropdownMenu aria-label="Profile Actions" variant="flat">
                        <DropdownItem aria-label={'profile-label'} key="profile" className="h-14 gap-2">
                            <p className="font-semibold">&nbsp;Hi,{nickname}</p>
                            <p className="font-semibold">📝 | 🤪 | 🧑‍💻</p>
                        </DropdownItem>
                        <DropdownItem aria-label={'divider-label'}>
                            <Divider orientation={'horizontal'}/>
                        </DropdownItem>
                        <DropdownItem aria-label={'personal_center-label'} key="personal_center" color={"default"}
                                      startContent={<BiMehBlank size={18}/>}
                                      onClick={onOpen}>个人中心</DropdownItem>
                        <DropdownItem aria-label={'settings-label'} key="settings" color={"default"}
                                      startContent={<BiCertification size={18}/>}
                                      onClick={() => onOpenSetChange(!isOpenSet)}>设置中心</DropdownItem>
                        <DropdownItem aria-label={'theme_switch-label'} key='theme_switch'
                                      startContent={<BiHotel size={18}/>}
                                      endContent={
                                          <Switch
                                              size="sm"
                                              color="secondary"
                                              isSelected={theme == 'light'}
                                              onValueChange={() => {
                                                  theme == 'light' ? setTheme('dark') : setTheme('light')
                                              }}
                                              thumbIcon={({isSelected, className}) =>
                                                  theme == 'light' ? (
                                                      <SunIcon className={className}/>
                                                  ) : (
                                                      <MoonIcon className={className}/>
                                                  )
                                              }
                                          />}>切换主题</DropdownItem>
                        <DropdownItem aria-label={'logout-label'} key="logout" color="danger"
                                      startContent={<BiLogOutCircle size={18}/>}
                                      onPress={() => {
                                          setExit(!isExit)
                                      }}>退出登录</DropdownItem>

                    </DropdownMenu>
                </Dropdown>
            </NavbarContent>
            {/*个人信息*/}
            <Modal backdrop={"blur"} isOpen={isOpen} onOpenChange={onOpenChange} placement={"auto"}>
                <ModalContent>
                    {
                        onClose => (
                            <>
                                <ModalHeader
                                    className={"flex flex-col gap-1 dark:text-white light:text-black "}>个人信息</ModalHeader>
                                <ModalBody>
                                    <div className={`flex justify-start items-center`}>
                                        <Avatar showFallback
                                                src={avatar}
                                                isBordered={true}
                                                onClick={handleChoosePhoto}
                                                fallback={
                                                    <AiFillCamera className="animate-pulse w-6 h-6 text-default-500"
                                                                  fill="currentColor" size={20}/>
                                                }

                                        />
                                    </div>
                                    <Spacer y={0.5}/>
                                    <Input
                                        readOnly={false}
                                        id={"nickname"}
                                        type={"text"}
                                        label={"名 称"}
                                        value={nickname}
                                        variant={"faded"}
                                        className={'dark:text-white'}
                                        placeholder={nickname}
                                        labelPlacement={"outside"}
                                        onValueChange={(v) => setNickname(v)}
                                        startContent={
                                            <CiFries
                                                className="text-2xl text-default-300 pointer-events-none flex-shrink-0"/>
                                        }

                                    />
                                    <Input
                                        isReadOnly
                                        id={'username'}
                                        type="text"
                                        label="用 户 名"
                                        variant={"faded"}
                                        placeholder={decodeFromBase64(cookie.load(UserName)).toString()}
                                        labelPlacement="outside"
                                        startContent={
                                            <FiUser
                                                className="text-2xl text-default-300 pointer-events-none flex-shrink-0"/>
                                        }
                                    />
                                    <Input
                                        isReadOnly
                                        id={'email'}
                                        type="email"
                                        label="邮 箱"
                                        variant={"faded"}
                                        placeholder={email}
                                        labelPlacement="outside"
                                        startContent={
                                            <MailIcon
                                                className="text-2xl text-default-300 pointer-events-none flex-shrink-0"/>
                                        }
                                    />
                                    <Input
                                        isReadOnly
                                        id={'regTime'}
                                        type="text"
                                        label="入 驻 期"
                                        variant={"faded"}
                                        placeholder={createTime}
                                        labelPlacement="outside"
                                        startContent={
                                            <MdMoreTime
                                                className="text-2xl text-default-300 pointer-events-none flex-shrink-0"/>
                                        }
                                    />
                                    {/*<Tooltip content={"账号安全认证码"} color={"danger"} className="capitalize"
                                             offset={15}
                                             delay={0}
                                             closeDelay={0}
                                             motionProps={{
                                                 variants: {
                                                     exit: {
                                                         opacity: 0,
                                                         transition: {
                                                             duration: 0.1,
                                                             ease: "easeIn",
                                                         }
                                                     },
                                                     enter: {
                                                         opacity: 1,
                                                         transition: {
                                                             duration: 0.15,
                                                             ease: "easeOut",
                                                         }
                                                     },
                                                 },
                                             }}
                                    >
                                        <Textarea
                                            isReadOnly
                                            id={'token'}
                                            className={"break-all"}
                                            type="text"
                                            label="安 全 码"
                                            variant={"flat"}
                                            placeholder={token}
                                            labelPlacement="outside"
                                            color={"danger"}
                                        />
                                    </Tooltip>*/}
                                </ModalBody>
                                <ModalFooter>
                                    <Button variant={"shadow"} color="default" onClick={(v) => {
                                        modifyUserInfo()
                                    }}>
                                        更 新 信 息
                                    </Button>
                                    <Button className={`w-1/3`} variant={"shadow"} color="primary" onClick={onClose}>
                                        Yee. 🤩
                                    </Button>
                                </ModalFooter>
                            </>
                        )
                    }
                </ModalContent>
            </Modal>
            {/*个人设置中心*/}
            <SettingPage isOpenSet={isOpenSet} onOpenSetChange={onOpenSetChange}/>
        </>
    )
}
